package com.ufo.store.management.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.OvershootInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.ufo.store.management.BarApplication;
import com.ufo.store.management.R;
import com.ufo.store.management.entity.StockInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  作者：taoli on 2017/6/6 0006 16:25
 *  
 */
public class StockRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Activity context = null;
    private List<StockInfo> mStockInfoList = null;
    private Map<String, String> mStockTypeMap = null;
    private OnClickListener mListener = null;
    private Typeface tf;
    private int mStyle;   // 1 : 列表   2： 网格
    private int lastPosition = -1;
    private int longPressedIndex = -1;
    private RequestOptions options;

    public StockRecyclerViewAdapter(Activity context, int style, Map<String, String> map) {
        this.context = context;
        this.mStyle = style;
        this.mStockInfoList = new ArrayList<StockInfo>();
        this.mStockTypeMap = map;
        tf = Typeface.createFromAsset(context.getAssets(), "OpenSans-Light.ttf");
        options = new RequestOptions();
        options.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC);
        options.skipMemoryCache(false);
        options.placeholder(R.drawable.ad7);
        options.error(R.drawable.ad7);
    }

    public void insertData(List<StockInfo> data) {
        mStockInfoList.addAll(data);
    }

    public void removeData(int pos) {
        mStockInfoList.remove(pos);
    }

    public void setData(List<StockInfo> data) {
        mStockInfoList.clear();
        mUrlMap.clear();
        mStockInfoList.addAll(data);
    }

    public void setMap(Map<String, String> map) {
        mStockTypeMap = map;
    }

    public Map<String, String> getMap() {
        return mStockTypeMap;
    }

    public void setStyle(int s) {
        mStyle = s;
    }

    public void setLongPressedIndex(int index) {
        longPressedIndex = index;
    }

    public int getLongPressedIndex() {
        return longPressedIndex;
    }

    public StockInfo getItem(int pos) {
        StockInfo info = mStockInfoList.get(pos);
        return info;
    }

    @Override
    public int getItemViewType(int position) {
        return mStyle;
    }

    @Override
    public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
        super.onViewDetachedFromWindow(holder);
        holder.itemView.clearAnimation();
    }

    /**
     * @desc 自定义动画
     * @author taoli
     * @time 2017/6/9 0009
     */
    private void setAnimation(View viewToAnimate, int position) {
        if (position > lastPosition) {
            Animation translateAnimation = new TranslateAnimation(0, 0, 100, 0);
            translateAnimation.setDuration(700);
            translateAnimation.setInterpolator(new OvershootInterpolator());
            viewToAnimate.setAnimation(translateAnimation);
            lastPosition = position;
        } else if (position < lastPosition) {
            Animation translateAnimation = new TranslateAnimation(0, 0, -100, 0);
            translateAnimation.setDuration(700);
            translateAnimation.setInterpolator(new OvershootInterpolator());
            viewToAnimate.setAnimation(translateAnimation);
            lastPosition = position;
        }
    }

    class RecyclerViewHolder extends RecyclerView.ViewHolder {
        ImageView stockIv;
        ImageView stockSecondaryIv;
        TextView stockNameTv;
        TextView stockTypeTv;
        TextView stockUnitTv;
        TextView stockBarcodeTv;
        TextView stockCostTv;
        TextView stockRetailPriceTv;
        TextView fuhao0Tv;
        TextView fuhao1Tv;
        ImageView menuIv;
        View maskV;
        TextView topTv;
        TextView bottomTv;

        public RecyclerViewHolder(View view) {
            super(view);
            stockIv = (ImageView) view.findViewById(R.id.stock_iv);
            stockSecondaryIv = (ImageView) view.findViewById(R.id.stock_secondary_iv);
            stockNameTv = (TextView) view.findViewById(R.id.stock_name_tv);
            stockTypeTv = (TextView) view.findViewById(R.id.stock_type_tv);
            stockUnitTv = (TextView) view.findViewById(R.id.stock_unit_tv);
            stockBarcodeTv = (TextView) view.findViewById(R.id.stock_barcode_tv);
            stockCostTv = (TextView) view.findViewById(R.id.stock_cost_tv);
            stockRetailPriceTv = (TextView) view.findViewById(R.id.stock_retail_price_tv);
            fuhao0Tv = (TextView) view.findViewById(R.id.fuhao0_tv);
            fuhao1Tv = (TextView) view.findViewById(R.id.fuhao1_tv);
            menuIv = (ImageView) view.findViewById(R.id.menu_iv);
            maskV = (View) view.findViewById(R.id.mask_v);
            topTv = (TextView) view.findViewById(R.id.top_iv);
            bottomTv = (TextView) view.findViewById(R.id.bottom_iv);
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder holder = null;
        if (viewType == 1) {
            holder = new RecyclerViewHolder(LayoutInflater.from(
                    this.context).inflate(R.layout.stock_listitem, parent,
                    false));
        } else if (viewType == 2) {
            holder = new RecyclerViewHolder(LayoutInflater.from(
                    this.context).inflate(R.layout.stock_recycleritem, parent,
                    false));
        }
        return holder;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        final StockInfo stockInfo = mStockInfoList.get(position);
        if (holder instanceof RecyclerViewHolder) {
            RecyclerViewHolder holder1 = (RecyclerViewHolder) holder;
            holder1.stockNameTv.setText(stockInfo.stockName.trim() + " | " + stockInfo.stockSpell.trim());
            //holder1.stockNameTv.setTypeface(tf);

            if (mStockTypeMap == null) {
                holder1.stockTypeTv.setVisibility(View.GONE);
            } else {
                holder1.stockTypeTv.setVisibility(View.VISIBLE);
                holder1.stockTypeTv.setText(mStockTypeMap.get(stockInfo.stockTpyeId).trim());
            }

            if (stockInfo.stockBarcode == null || stockInfo.stockBarcode.length() == 0) {
                holder1.stockBarcodeTv.setText("条码");
               // holder1.stockBarcodeTv.setTypeface(tf);
                holder1.stockBarcodeTv.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG| Paint.ANTI_ALIAS_FLAG);     // 设置中划线并加清晰 
            } else {
                holder1.stockBarcodeTv.setText(stockInfo.stockBarcode);
                //holder1.stockBarcodeTv.setTypeface(tf);
                holder1.stockBarcodeTv.getPaint().setFlags(0);              // 取消设置的的划线
            }

           // holder1.fuhao0Tv.setTypeface(tf);
           // holder1.fuhao1Tv.setTypeface(tf);
            holder1.stockRetailPriceTv.setText(String.valueOf(stockInfo.stockDetailPrice));
           // holder1.stockRetailPriceTv.setTypeface(tf);
            holder1.stockCostTv.setText(String.valueOf(stockInfo.stockCost));
           // holder1.stockCostTv.setTypeface(tf);

            if (BarApplication.getInstance().mbStockDisplayCost)
                holder1.stockCostTv.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            else
                holder1.stockCostTv.setTransformationMethod(PasswordTransformationMethod.getInstance());

            if (BarApplication.getInstance().mbStockDisplayPicture)
                getPicDesc(position, stockInfo.stockId.trim(), holder1.stockIv, holder1.stockSecondaryIv);

            if (!holder1.menuIv.hasOnClickListeners()) {
                holder1.menuIv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int pos = holder.getPosition();
                        mListener.onMenuClick(v, pos);
                    }
                });
            }

            if (!holder1.maskV.hasOnClickListeners()) {
                holder1.maskV.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int pos = holder.getPosition();
                        mListener.onMaskClick(v, pos);
                    }
                });
            }

            if (!holder1.topTv.hasOnClickListeners()) {
                holder1.topTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int pos = holder.getPosition();
                        mListener.onDeleteClick(pos);
                    }
                });
            }

            if (!holder1.bottomTv.hasOnClickListeners()) {
                holder1.bottomTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int pos = holder.getPosition();
                        mListener.onDetailClick(pos);
                    }
                });
            }

            holder1.maskV.setVisibility(View.GONE);
            holder1.topTv.setVisibility(View.GONE);
            holder1.bottomTv.setVisibility(View.GONE);
            holder1.maskV.clearAnimation();
            holder1.topTv.clearAnimation();
            holder1.bottomTv.clearAnimation();
        }

        //进入动画
        setAnimation(holder.itemView, position);

        //点击事件
        if (mListener != null) {
            /**
             * 这里加了判断，itemViewHolder.itemView.hasOnClickListeners()
             * 目的是减少对象的创建，如果已经为view设置了click监听事件,就不用重复设置了
             * 不然每次调用onBindViewHolder方法，都会创建两个监听事件对象，增加了内存的开销
             */
            if (!holder.itemView.hasOnClickListeners()) {
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int pos = holder.getPosition();
                        mListener.onItemClick(v, pos);
                    }
                });
                holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        int pos = holder.getPosition();
                        mListener.onItemLongClick(v, pos);
                        return true;
                    }
                });
            }
        }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position, List payloads) {
        if (payloads.isEmpty()) {
            onBindViewHolder(holder, position);
        } else {
            if (holder instanceof RecyclerViewHolder) {
                String payload = (String) payloads.get(0);
                final RecyclerViewHolder holder1 = (RecyclerViewHolder) holder;
                if (payload.equals("recovery")) {
                    AnimationSet master_toappear_animation = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.master_toappear);
                    holder1.stockIv.startAnimation(master_toappear_animation);
                    AnimationSet secondary_todisappear_animation = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.secondary_todisappear);
                    holder1.stockSecondaryIv.startAnimation(secondary_todisappear_animation);
                } else if (payload.equals("exhibit")) {
                    AnimationSet master_todisappear_animation = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.master_todisappear);
                    holder1.stockIv.startAnimation(master_todisappear_animation);
                    AnimationSet secondary_toappear_animation = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.secondary_toappear);
                    holder1.stockSecondaryIv.startAnimation(secondary_toappear_animation);
                    holder1.stockSecondaryIv.setAlpha(1.0f);
                }else if(payload.equals("menu")){
                    if (longPressedIndex != -1 && position == longPressedIndex) {
                        holder1.maskV.setVisibility(View.VISIBLE);
                        holder1.topTv.setVisibility(View.VISIBLE);
                        holder1.bottomTv.setVisibility(View.VISIBLE);
                        AnimationSet showAnimationSet = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.jump_toshow_anim);
                        holder1.maskV.startAnimation(showAnimationSet);
                        if (mStyle == 1) {
                            AnimationSet leftAnimationSet = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.jump_toleft_anim);
                            AnimationSet rightAnimationSet = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.jump_toright_anim);
                            holder1.topTv.startAnimation(leftAnimationSet);
                            holder1.bottomTv.startAnimation(rightAnimationSet);
                        } else if (mStyle == 2) {
                            AnimationSet topAnimationSet = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.jump_totop_anim);
                            AnimationSet bottomAnimationSet = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.jump_tobottom_anim);
                            holder1.topTv.startAnimation(topAnimationSet);
                            holder1.bottomTv.startAnimation(bottomAnimationSet);
                        }
                    } else {
                        if ( mStyle == 1 ) {
                            AnimationSet leftToCenterAnimationSet = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.jump_lefttocenter_anim);
                            leftToCenterAnimationSet.setAnimationListener(new Animation.AnimationListener() {
                                @Override
                                public void onAnimationStart(Animation animation) {

                                }

                                @Override
                                public void onAnimationEnd(Animation animation) {
                                    holder1.topTv.setVisibility(View.GONE);
                                }

                                @Override
                                public void onAnimationRepeat(Animation animation) {

                                }
                            });
                            holder1.topTv.startAnimation(leftToCenterAnimationSet);

                            AnimationSet rightToCenterAnimationSet = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.jump_righttocenter_anim);
                            rightToCenterAnimationSet.setAnimationListener(new Animation.AnimationListener() {
                                @Override
                                public void onAnimationStart(Animation animation) {

                                }

                                @Override
                                public void onAnimationEnd(Animation animation) {
                                    holder1.bottomTv.setVisibility(View.GONE);
                                }

                                @Override
                                public void onAnimationRepeat(Animation animation) {

                                }
                            });
                            holder1.bottomTv.startAnimation(rightToCenterAnimationSet);
                        }else if( mStyle == 2 ) {
                            AnimationSet topToCenterAnimationSet = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.jump_toptocenter_anim);
                            topToCenterAnimationSet.setAnimationListener(new Animation.AnimationListener() {
                                @Override
                                public void onAnimationStart(Animation animation) {

                                }

                                @Override
                                public void onAnimationEnd(Animation animation) {
                                    holder1.topTv.setVisibility(View.GONE);
                                }

                                @Override
                                public void onAnimationRepeat(Animation animation) {

                                }
                            });
                            holder1.topTv.startAnimation(topToCenterAnimationSet);

                            AnimationSet bottomToCenterAnimationSet = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.jump_bottomtocenter_anim);
                            bottomToCenterAnimationSet.setAnimationListener(new Animation.AnimationListener() {
                                @Override
                                public void onAnimationStart(Animation animation) {

                                }

                                @Override
                                public void onAnimationEnd(Animation animation) {
                                    holder1.bottomTv.setVisibility(View.GONE);
                                }

                                @Override
                                public void onAnimationRepeat(Animation animation) {

                                }
                            });
                            holder1.bottomTv.startAnimation(bottomToCenterAnimationSet);
                        }
                        holder1.maskV.setVisibility(View.GONE);
                        holder1.maskV.clearAnimation();
                    }
                }
            }
        }
    }

    @Override
    public int getItemCount() {
        return mStockInfoList.size();
    }

    public void setOnClickListener(OnClickListener l) {
        mListener = l;
    }

    public interface OnClickListener {
        void onDeleteClick(int position);

        void onDetailClick(int position);

        void onItemClick(View v, int position);

        void onItemLongClick(View v, int position);

        void onMenuClick(View v, int position);

        void onMaskClick(View v, int position);
    }


    private HashMap<String, Object> mUrlMap = new HashMap<String, Object>();

    private void getPicDesc(final int position, final String stockId, final ImageView iv, final ImageView ivCopy) {
        String downloadRUL = BarApplication.Qiniu_BaseDownloadHost + BarApplication.mStoreName + "_" + "stockNo_" + stockId + ".jpg";
        RequestListener listener = new RequestListener<Drawable>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(Drawable drawable, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
                //if (dataSource == DataSource.MEMORY_CACHE) {
                //当图片位于内存缓存时，glide默认不会加载动画
                iv.startAnimation(AnimationUtils.loadAnimation(context, R.anim.fadein));
                //}
                return false;
            }
        };
        Glide.with(context).load(downloadRUL).apply(options).listener(listener).thumbnail(0.1f).into(iv);
        Glide.with(context).load(downloadRUL).apply(options).thumbnail(0.1f).into(ivCopy);

        StockInfo info = mStockInfoList.get(position);
        info.url = downloadRUL;
    }
}
